package cn.itcast.service.impl;

import cn.itcast.common.R;
import cn.itcast.entity.Employee;
import cn.itcast.entity.Page;
import cn.itcast.mapper.IEmployeeMapper;
import cn.itcast.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static cn.itcast.common.R.error;
import static cn.itcast.common.R.success;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired(required = false)
    private IEmployeeMapper employeeMapper;

    /**
     * 登录
     * @param employee
     * @return
     */
    @Override
    public R<Employee> login(Employee employee) {
        Employee dBEmployee= employeeMapper.fingByUsername( employee);
        //用户名不存在
        if (dBEmployee == null){
          return error("用户名不存在");

        }
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes(StandardCharsets.UTF_8));
        //密码不正确
        if (!dBEmployee.getPassword().equals(password)){
            return error("密码错误");
        }
        //账户禁用
        if (dBEmployee.getStatus() ==0){
            return error("账户被禁用");
        }


        return success(dBEmployee);
    }

    /**
     * 插入一条数据
     *
     * @param employee
     */
    @Override
    public void save(Employee employee) {
        employeeMapper.save(employee);
    }

    /**
     * 查询页面数据
     *
     * @param page     第几页
     * @param pageSize 页面容量
     * @param name     搜索文本
     * @return
     */
    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        List<Employee> employees = employeeMapper.findByName(name);
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);

        return new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageSize,page);
    }

    /**
     * 修改数据 状态或者修改员工信息
     *
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }
}
